package response

import (
	"encoding/json"
	"net/http"
	"zzxq/common/codes"

	"github.com/gin-gonic/gin"
)

var _respKey = "globalrepsonse"

type result struct {
	ctx *gin.Context

	responseJson
}

//工厂方法创建返回值实例
func NewResponse(ctx *gin.Context) *result {
	return &result{ctx: ctx}
}

type responseJson struct {
	Status int `json:"status"`
	Msg    string `json:"msg"`
	Data   interface{} `json:"data"`
}

//统一参数格式
type withResponse interface{}

//提供消息
func (r *result) WithMsg(msg string) withResponse {
	r.responseJson.Msg = msg

	return nil
}

//提供data
func (r *result) WithData(data interface{}) withResponse {
	r.responseJson.Data = data

	return nil
}

//统一返回值
func (r *result) Resp(status int, opts ...withResponse) {
	r.responseJson.Status = status

	//status 3000-4000 是自定义消息
	if r.responseJson.Msg == "" {
		r.responseJson.Msg = codes.GetMsg((status))
	}

	jsonStr(r.ctx, r.responseJson)
}

//失败返回值
func RespF(c *gin.Context, status int, msg string) {
	res := responseJson{}
	res.Status = status

	switch {
	case status > 2999 && status < 4000: //自定义消息
		res.Msg = msg
	default:
		res.Msg = codes.GetMsg(status)
	}

	jsonStr(c, res)
}

//成功返回值
func RespS(c *gin.Context, data interface{}) {
	res := responseJson{}
	res.Status = codes.SUCCESS
	res.Msg = codes.GetMsg(res.Status)
	res.Data = data

	jsonStr(c, res)
}

//统一返回值中间件
func ResponseMiddleware() gin.HandlerFunc {
	return func (c *gin.Context) {

		c.Next()

		result := c.GetString(_respKey)
		c.String(http.StatusOK, result)
		c.Abort()
	}
}

//设置系列化后的数据
func jsonStr(c *gin.Context, data interface{}) {
	jsonStrs, err := json.Marshal(data);
	if err != nil {
		c.Set(_respKey, "系统异常")
	}

	c.Set(_respKey, string(jsonStrs))
}